import { defineStore } from 'pinia'
import { getMenus } from '@/api/auth/user'

interface RoutesState {
  menuList: any
  routeList: any
  tabList: any
  activeTab: string
}

const useRoutesStore = defineStore('routes', {
  state: (): RoutesState => ({
    menuList: [],
    routeList: [],
    tabList: [{ title: '首页', path: 'home/index' }],
    //当前钻中tab，通过path体现
    activeTab: 'home/index'
  }),
  getters: {},
  actions: {
    async setMenus() {
      const userMenusResult = await getMenus()
      const userMenus = userMenusResult.data
      this.menuList = userMenus
    },
    //渲染动态路由数据结构，存储到pinia中，不需要每次都去渲染数据结构了
    //data就是查询出来的菜单数据
    setRouteList(data: any) {
      data.forEach((item: any) => {
        const routeInfo = {
          name: item.MenuName,
          path: item.path,
          meta: { title: item.menuName },
          component: () => import(/*@vite-ignore */ `/src/views/${item.path}.vue`)
        }
        this.routeList.push(routeInfo)

        const childrenList = item.children

        childrenList.forEach((children: any) => {
          const routeInfo = {
            name: children.MenuName,
            path: children.path,
            meta: { title: children.menuName },
            component: () => import(/*@vite-ignore */ `/src/views/${children.path}.vue`)
          }
          this.routeList.push(routeInfo)
        })
      })
    },
    //设置tabList{title:'首页',path：'/home/index'}
    setTabList(data: any) {
      this.tabList.push(data)
    },
    delTabList(name: any) {
      this.tabList = this.tabList.filter((item: any) => {
        if (item.path == name) {
          return false
        } else {
          return true
        }
      })
    },
    setActiveTab(name: any) {
      this.activeTab = name
    }
  }
})

export default useRoutesStore
